package com.centerserver;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.DefaultListModel;
import javax.swing.table.DefaultTableModel;

class ProcessMonitorCommandThread extends Thread {
	
	private DefaultTableModel mMsgTableModel;
	private Socket mSocket;
	public ProcessMonitorCommandThread(DefaultTableModel msgTableModel, Socket socket) {
		mMsgTableModel = msgTableModel;
		mSocket = socket;
	}
	
	@Override
	public void run() {
		
		try {
			InputStream inputStream = mSocket.getInputStream();
			MonitorCommand monitorCommand = new MonitorCommand();
			
			// set the time
			Date date = Calendar.getInstance().getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
			monitorCommand.mTime = sdf.format(date);
			
			int ipAddrLen; 
			byte[] ipAddr;
			
			// set the sender 
			ipAddrLen = inputStream.read();
			ipAddr = new byte[ipAddrLen];
			inputStream.read(ipAddr, 0, ipAddrLen);
			monitorCommand.mSender = new String(ipAddr, "ISO-8859-1");
			
			int recvNameLen;
			byte[] recvName;
			
			// set the receiver
			recvNameLen = inputStream.read();
			recvName = new byte[recvNameLen];
			inputStream.read(recvName, 0, recvNameLen);
			monitorCommand.mReceiver = new String(recvName, "ISO-8859-1");
			
			
			int commandTypeLen;
			byte[] commandType;
			
			// set the command type
			commandTypeLen = inputStream.read();
			commandType = new byte[commandTypeLen];
			inputStream.read(commandType, 0, commandTypeLen);
			monitorCommand.mCommandType = new String(commandType, "ISO-8859-1");
			
			int argumentLen;
			byte[] argument;
			
			// set the argument1
			argumentLen = inputStream.read();
			argument = new byte[argumentLen];
			inputStream.read(argument, 0, argumentLen);
			monitorCommand.mArgument1 = new String(argument, "ISO-8859-1");
			
			// set the argument2
			argumentLen = inputStream.read();
			argument = new byte[argumentLen];
			inputStream.read(argument, 0, argumentLen);
			monitorCommand.mArgument2 = new String(argument, "ISO-8859-1");
			
			// set the argument3
			argumentLen = inputStream.read();
			argument = new byte[argumentLen];
			inputStream.read(argument, 0, argumentLen);
			monitorCommand.mArgument3 = new String(argument, "ISO-8859-1");
			
			updateMsgTab(monitorCommand);
			
			
		} catch (IOException e) {
			System.out.println("IOException in ProcessMonitorCommand");
			e.printStackTrace();
		}
	}
	
	private void updateMsgTab(MonitorCommand monitorCommand) {
		
		Object[] msg = new Object[] {
				monitorCommand.mTime,
				monitorCommand.mSender,
				monitorCommand.mReceiver,
				monitorCommand.mCommandType,
				monitorCommand.mArgument1,
				monitorCommand.mArgument2,
				monitorCommand.mArgument3,
		};
		
		mMsgTableModel.addRow(msg);
	}
}
